/* **************************************************
 Copyright (c) 2012, University of Cambridge
 Neal Lathia, neal.lathia@cl.cam.ac.uk
 Kiran Rachuri, kiran.rachuri@cl.cam.ac.uk

This library was developed as part of the EPSRC Ubhave (Ubiquitous and
Social Computing for Positive Behaviour Change) Project. For more
information, please visit http://www.emotionsense.org

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ************************************************** */

package com.ubhave.sensormanager.sensors.push;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.data.push.PhoneStateData;
import com.ubhave.sensormanager.process.push.PhoneStateProcessor;
import com.ubhave.sensormanager.sensors.SensorUtils;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.dcall.CallStateObserver;
import ohos.dcall.DistributedCallManager;
import ohos.event.commonevent.MatchingSkills;
import ohos.telephony.*;

import java.util.List;

public class PhoneStateSensor extends AbstractPushSensor {
    private static final String TAG = "PhoneStateSensor";
    private static final String[] REQUIRED_PERMISSIONS = new String[]{
//            "ohos.permission.GET_TELEPHONY_STATE", "ohos.permission.LOCATION", "ohos.permission.PLACE_CALL"
    };
    private final CellularDataInfoManager cellularDataInfoManager;
    private final CellularDataStateObserver cellularDataStateObserver;
    private final CallStateObserver callStateObserver;

    private RadioInfoManager telephonyManager;
    private DistributedCallManager callManager;
    private RadioStateObserver phoneStateListener;

    private volatile static PhoneStateSensor phoneStateSensor;
    private static Object lock = new Object();

    public static PhoneStateSensor getSensor(final Context context) throws ESException {
        PhoneStateSensor localPhoneStateSensor = phoneStateSensor;
        if (localPhoneStateSensor == null) {
            synchronized (lock) {
                localPhoneStateSensor = phoneStateSensor;
                if (localPhoneStateSensor == null) {
                    if (allPermissionsGranted(context, REQUIRED_PERMISSIONS)) {
                        phoneStateSensor = localPhoneStateSensor = new PhoneStateSensor(context);
                    } else throw new ESException(ESException.PERMISSION_DENIED, SensorUtils.SENSOR_NAME_PHONE_STATE);
                }
            }
        }
        return phoneStateSensor;
    }

    private PhoneStateSensor(final Context context) {
        super(context);
        telephonyManager = RadioInfoManager.getInstance(context);
        callManager = DistributedCallManager.getInstance(context);

        cellularDataInfoManager = CellularDataInfoManager.getInstance(context);
        callStateObserver = new CallStateObserver() {
            @Override
            public void onVoiceMailMsgIndicatorUpdated(boolean isExist) {
                super.onVoiceMailMsgIndicatorUpdated(isExist);
            }

            @Override
            public void onCfuIndicatorUpdated(boolean enable) {
                super.onCfuIndicatorUpdated(enable);
            }

            @Override
            public void onCallStateUpdated(int state, String number) {
                super.onCallStateUpdated(state, number);
                String stateString = "N/A";
                int stateType = 0;
                switch (state) {
                    case CallStateObserver.CALL_STATE_IDLE:
                        stateType = PhoneStateData.CALL_STATE_IDLE;
                        stateString = "CALL_STATE_IDLE";
                        break;
                    case CallStateObserver.CALL_STATE_OFFHOOK:
                        stateType = PhoneStateData.CALL_STATE_OFFHOOK;
                        stateString = "CALL_STATE_OFFHOOK";
                        break;
                    case CallStateObserver.CALL_STATE_RINGING:
                        stateType = PhoneStateData.CALL_STATE_RINGING;
                        stateString = "CALL_STATE_RINGING";
                        break;
                }

                logOnDataSensed(stateType, stateString, number);

            }
        };

        cellularDataStateObserver = new CellularDataStateObserver(CellularDataStateObserver.OBSERVE_MASK_DATA_CONNECTION_STATE) {
            @Override
            public void onCellularDataFlow(int direction) {
                super.onCellularDataFlow(direction);
                logOnDataSensed(PhoneStateData.ON_DATA_ACTIVITY, getDataActivityString(direction), null);
            }

            @Override
            public void onCellularDataConnectStateUpdated(int state, int networkType) {
                super.onCellularDataConnectStateUpdated(state, networkType);
                logOnDataSensed(PhoneStateData.ON_DATA_CONNECTION_STATE_CHANGED, getDataConnectionStateString(state), null);
            }
        };

        phoneStateListener = new RadioStateObserver(RadioStateObserver.OBSERVE_MASK_NETWORK_STATE) {

            @Override
            public void onNetworkStateUpdated(NetworkState networkState) {
                super.onNetworkStateUpdated(networkState);
                if (networkState != null) {
                    String serviceStateStr = getServiceStateString(networkState.getRegState());
                    logOnDataSensed(PhoneStateData.ON_SERVICE_STATE_CHANGED, serviceStateStr + " " + networkState.toString(), null);
                }
            }

            @Override
            public void onSignalInfoUpdated(List<SignalInformation> signalInfos) {
                super.onSignalInfoUpdated(signalInfos);
            }

        };

    }

    @Override
    protected void onBroadcastReceived(Context context, Intent intent) {
        /*String outgoingNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);*/
        String outgoingNumber = "15337286666";
        logOnDataSensed(PhoneStateData.CALL_STATE_OUTGOING, "CALL_STATE_OUTGOING ", outgoingNumber);
    }

    private void logOnDataSensed(int eventType, String data, String number) {
        if (isSensing) {
            PhoneStateProcessor processor = (PhoneStateProcessor) getProcessor();
            if (processor != null) {
                PhoneStateData phoneStateData = processor.process(System.currentTimeMillis(), sensorConfig.clone(), eventType, data, number);
                onDataSensed(phoneStateData);
            }
        }
    }

    protected MatchingSkills getIntentFilters() {
        MatchingSkills skills = new MatchingSkills();
        skills.addEvent("android.intent.action.NEW_OUTGOING_CALL");
        return skills;
    }

    public static String getServiceStateString(int serviceState) {
        switch (serviceState) {
            case NetworkState.REG_STATE_EMERGENCY_CALL_ONLY:
                return "STATE_EMERGENCY_ONLY";
            case NetworkState.REG_STATE_IN_SERVICE:
                return "STATE_IN_SERVICE";
            case NetworkState.REG_STATE_NO_SERVICE:
                return "STATE_OUT_OF_SERVICE";
            case NetworkState.REG_STATE_POWER_OFF:
                return "STATE_POWER_OFF";
            default:
                return "";
        }
    }

    public static String getDataActivityString(int direction) {
        switch (direction) {
            case CellularDataInfoManager.DATA_FLOW_TYPE_NONE:
                return "DATA_ACTIVITY_NONE";
            case CellularDataInfoManager.DATA_FLOW_TYPE_UP:
                return "DATA_ACTIVITY_IN";
            case CellularDataInfoManager.DATA_FLOW_TYPE_DOWN:
                return "DATA_ACTIVITY_OUT";
            case CellularDataInfoManager.DATA_FLOW_TYPE_UPDOWN:
                return "DATA_ACTIVITY_INOUT";
            case CellularDataInfoManager.DATA_FLOW_TYPE_DORMANT:
                return "DATA_ACTIVITY_DORMANT";
            default:
                return "";
        }
    }

    public static String getDataConnectionStateString(int dataConnectionState) {
        switch (dataConnectionState) {
            case CellularDataInfoManager.DATA_STATE_DISCONNECTED:
                return "DATA_DISCONNECTED";
            case CellularDataInfoManager.DATA_STATE_CONNECTING:
                return "DATA_CONNECTING";
            case CellularDataInfoManager.DATA_STATE_CONNECTED:
                return "DATA_CONNECTED";
            case CellularDataInfoManager.DATA_STATE_SUSPENDED:
                return "DATA_SUSPENDED";
            default:
                return "";
        }
    }

    protected String getLogTag() {
        return TAG;
    }

    public int getSensorType() {
        return SensorUtils.SENSOR_TYPE_PHONE_STATE;
    }

    protected boolean startSensing() {
        int interestedEvents = RadioStateObserver.OBSERVE_MASK_CELL_INFO | RadioStateObserver.OBSERVE_MASK_NETWORK_STATE | RadioStateObserver.OBSERVE_MASK_SIGNAL_INFO;
        telephonyManager.addObserver(phoneStateListener, interestedEvents);
        cellularDataInfoManager.addObserver(cellularDataStateObserver, RadioStateObserver.OBSERVE_MASK_CELL_INFO);
        callManager.addObserver(callStateObserver, CallStateObserver.OBSERVE_MASK_CALL_STATE);
        return true;
    }

    protected void stopSensing() {
        telephonyManager.removeObserver(phoneStateListener);
        cellularDataInfoManager.removeObserver(cellularDataStateObserver);
        callManager.removeObserver(callStateObserver);
    }

}
